<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/7/15 16:01
 */

namespace App\Project\Traits;

use App\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 用户认证后，的跳转地址
 * Trait RedirectsUsers
 * @package App\Project\Traits
 */
trait RedirectsUsers
{
    /**
     * @param \Illuminate\Http\Request $request
     * @param \App\User                $user
     * @return bool|string
     */
    public function redirectPath(Request $request, User $user)
    {
        if (method_exists($this, 'redirectTo')) {
            return $this->redirectTo();
        }

        return property_exists($this, 'redirectTo')
            ? $this->redirectTo
            : $this->defaultUrl($request, $user);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \App\User                $user
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|static
     */
    protected function authenticated(Request $request, User $user)
    {
        if ($request->wantsJson()) {
            $url = $this->defaultUrl($request, $user);

            if (false == $user) {
                return response()->json(['message' => '该账号密码目前不可用'], 422);
            }

            return $this->sendSuccessResponse($url);
        }

        return redirect()->intended($this->redirectPath($request, $user));
    }

    /**
     * @param $url
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendSuccessResponse($url)
    {
        return JsonResponse::create(
            [
                'data'    => [
                    'url' => $url
                ],
                'message' => '执行成功',
                'code'    => '10000'
            ]);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \App\User                $user
     * @return bool|string
     */
    protected function defaultUrl(Request $request, User $user)
    {
        if (!$user->isPatient()) {

            return route('dashboard.index');
        } else {
            //  将来修改为 患者端登录后的地址 目前提示 不可用
            return false;
        }
    }
}